import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useStore = defineStore('main', () => {
    const token = ref('')
    const user = ref({})
    const isUserList= ref(false)
    const setToken = (newToken) => {
        token.value = newToken
    }
    
    const setUser = (userData) => {
        user.value = userData
    }

    const clearToken = () => {
        token.value = ''
        user.value = {}
    }
    const getUserInfo = () => {
        return user.value
    }
    const getIsUserList = () => {
        return isUserList.value
    }
    return {
        token,
        user,
        isUserList,
        setToken,
        setUser,
        clearToken,
        getUserInfo,
        getIsUserList
    }
}, {
    persist: {
        key: 'main',
        storage: localStorage,
        paths: ['token', 'user'],
        serializer: {
            serialize: (value) => JSON.stringify(value),
            deserialize: (value) => {
                try {
                    const data = JSON.parse(value)
                    return {
                        token: data.token || '',
                        user: data.user || {}
                    }
                } catch {
                    return { token: '', user: {} }
                }
            }
        }
    }
})